package top.alanshelby.utils;

import top.alanshelby.service.impl.ISomeService;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MyBeanPostProcessor1 implements BeanPostProcessor {

    public Object postProcessBeforeInitialization(Object bean, String beanName) throws Exception {
        System.out.println("bean 对象初始化之前······");
        return bean;
        // return bean对象监控代理对象
    }

    public Object postProcessAfterInitialization(final Object beanInstance, String beanName) throws Exception {
        // 为当前 bean 对象注册监控代理对象，负责增强 bean 对象方法的能力
        Class beanClass = beanInstance.getClass();
        if (beanClass == ISomeService.class) {
            Object proxy = Proxy.newProxyInstance(beanInstance.getClass().getClassLoader(),
                    beanInstance.getClass().getInterfaces(),
                    new InvocationHandler() {
                        /**
                         * @param proxy 代理监控对象
                         * @param method doSome()方法
                         * @param args doSome()方法执行时接收的实参
                         * @return
                         * @throws Throwable
                         */
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            System.out.println("ISomeService 中的 doSome() 被拦截了···");
                            String result = (String) method.invoke(beanInstance, args);
                            return result.toUpperCase();
                        }
                    });
            return proxy;
        }
        return beanInstance;
    }
}
